<?php

abstract class table extends base {
  
  private static $CLASS_NAME    = null;
  private static $TABLE_NAME    = null;
  private static $TABLE_FIELDS  = array();
  private static $PRIMARY_KEY   = array();
  
  /**
   * @return string 
   */
  public static function getClassName($className){
    return $className;
  }
  
  /**
   * @return string 
   */
  public static function getTableName($className){
    $tn='';
    switch($className){
      case 'membre':
        $tn = membre::$TABLE_NAME;
        break;
      case 'match':
        $tn = match::$TABLE_NAME;
        break;
      case 'news':
        $tn = news::$TABLE_NAME;
        break;
    }
    return $tn;
  }
  
  public static function getPrimaryKey($tableName){
    $info  = self::_getTableInfo($tableName);
    return $info['PK'];
  }

  public static function getFields($tableName){
    $info  = self::_getTableInfo($tableName);
    return $info['TF'];
  }
  
  /**
   * @param string $key
   * @return mixed 
   */
  public static function getInSession($key,$tableName){
    if(!is_null($key)){
      $ret = $_SESSION['lolita']['tables'][$tableName][$key];
    } else {
      $ret=null;
      if(isset($_SESSION['lolita']['tables'][$tableName])){
        $ret = $_SESSION['lolita']['tables'][$tableName];
      }
    }
    return $ret;
  }

  /**
   *
   * @param string $key
   * @param mixed $value
   * @return type 
   */
  public static function setInSession($key,$value,$tableName){
    $_SESSION['lolita']['tables'][$tableName][$key] = $value;
  }
  
  private static function _getTableInfo($tableName){
    $info = self::getInSession(null,$tableName);
    
    if(!empty($info)){
      return $info;
    }
    
    $db = self::getDb();
    $sql = sprintf('SHOW COLUMNS FROM %s',$tableName);
    $info['TF']=array();
    $info['PK']=array();
    $fields = $db->SelectAll($sql);
    foreach($fields as $field){
      $info['TF'][] = $field['Field'];
      if($field['Key']=='PRI'){
        $info['PK'][] = $field['Field'];
      }
    }
    
    if(!is_array($info['TF']) || count($info['PK'])==0){
      throw new Exception(sprintf('Impossible de récuperer la définition de %s',$tableName));
    }
    
    self::setInSession('TF', $info['TF'], $tableName);
    self::setInSession('PK', $info['PK'], $tableName);
    
    return $info;
    
  }
  
  private static function _getTableFields(){
    if(!is_array(self::$TABLE_FIELDS )  || count(self::$TABLE_FIELDS)==0){
      self::_getTableInfo();
    }
    if(!is_array(self::$TABLE_FIELDS)   || count(self::$TABLE_FIELDS)==0){
      throw new Exception(sprintf('Impossible de récuperer les champs de la table %s',self::getTableName()));
    }
    
    return self::$TABLE_FIELDS;
  }
  
  private static function _getKeyFields(){
    
    if(!is_array(self::getPrimaryKey()) || count(self::getPrimaryKey())==0){
      self::_getTableInfo();
    }
    
    if(!is_array(self::getPrimaryKey()) || count(self::getPrimaryKey())==0){
      throw new Exception(sprintf('Impossible de récuperer la clé primaire de %s',self::getTableName()));
    }
    
    return self::getPrimaryKey();
  }
  
  /**
   *
   * @param array $array
   * @return table 
   */
  public static function newItem($array,$className){
    $c = self::getClassName($className);
    
    return new $c($array);
  }
  
  public static function getAll($sql=null,$fields='*'){
    
    $c = self::getClassName();
    
    if($sql==null){
      $sql  = sprintf('SELECT %s from %s',$fields,self::getTableName());
    }
    $db = self::getDb();
    $ret = null;
    foreach($db->SelectAll($sql) as $item){
      $ret[] = self::newItem($item);
    }
    return $ret;
  }

  public static function addSlashes($what){
    return addslashes($what);
  }
  /**
   *
   * @return string 
   */
  public static function getPrimaryKeyFields(){
    //$c    = self::getClassName();
    $keys = self::_getKeyFields();
    
    if(!is_array($keys)){
      $keys= array($keys);
    }
    foreach($keys as $key ){
      $ret[]=$key . '="'.self::addSlashes($this->$key).'"';
    }
    
    $ret = join(' AND ', $ret);
    return $ret;
  }
  
  public function update($fieldNames='*',$className){
      
      $c      = self::getClassName($className);
      $table  = self::getTableName($c);
      $keys   = self::getPrimaryKey($table);
      $db     = self::getDb();
      
      if($fieldNames=='*' || $fieldNames==''){
        $fieldNames = self::getFields($table);
      }
      
      if(!is_array($fieldNames)){
        $fieldNames = array($fieldNames);
      }
      
      $sets = array();
      
      foreach($fieldNames as $fieldName=>$value){
        
        if(is_int($fieldName) && isset($this->$value)){
          $fieldName  = $value;
          $value      = $this->$fieldName;
          
          if(commun::isFrenchDate($value)){
            $value = commun::dateToEtad($value);
          }
        }
        
        if(isset($this->$fieldName)){
          $val    = self::addSlashes($value);
          $sets[] = sprintf('`%s` = "%s"',$fieldName,$val);
        }
      }
      
      $sets = join(',', $sets);
      
      if($sets!=''){
        
        $where = array();
        
        foreach($keys as $key){
          $value  = $this->$key;
          $where[]=  sprintf('`%s` = "%s"',$key,self::addSlashes($value));
        }
        
        $sql    = sprintf('UPDATE `%s` set %s where %s',$table,$sets,join('and',$where));
        $ret    = $db->Update($sql);
      }
      
    return $ret;  
    
  }
  
  public function insert($className){
    $c      = self::getClassName($className);
    $table  = self::getTableName($c);
    $keys   = self::getPrimaryKey($table);
    $db     = self::getDb();
    
    $fieldNames = self::getFields($table);
    
    $sets   = array();
    $names  = array();
    $values = array();

    foreach($fieldNames as $key=>$value){

      if(is_int($key) && isset($this->$value)){
        $fieldName  = $value;
        $value      = $this->$value;

        if(isset($fieldName) && !is_null($value) ){
          $names[]  = $fieldName;
          if(!commun::isFrenchDate($value)){
            $val  = '"'.self::addSlashes($value).'"';
          } else {
            $val  = '"'.commun::dateToEtad($value).'"';
          }
          $values[] = $val;
        }
      }
    }

    if(!empty($names) && !empty($values)){
      
      $sql = sprintf("INSERT INTO %s (%s) VALUES(%s);",$table,join(',', $names),join(',', $values));
      
      $ret    = $db->Insert($sql);
      if($ret){
        $ret=$db->lastId;
      }
    }
    
    return $ret;  
    
  }

  
}

